<?php


namespace app\privatearea\controller\v1;


use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\privatearea\PrivateAreaGoods;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\cachemodel\privatearea\PrivateAreaQuestionInfo;
use app\common\lib\exception\ApiException;
use app\common\lib\PushQueue;
use app\privatearea\controller\Auth;
use think\Db;
use think\Log;
use think\response\Json;

class Order extends Auth
{
    /**
     * 获取商品信息【订单确认页】
     */
    public function orderCheck()
    {
        $qid = input('qid/d', 0);

        $questionInfoModel = new PrivateAreaQuestionInfo();
        $goodModel = new PrivateAreaGoods();

        $questionData = $questionInfoModel->getPrivateAreaQuestionInfo($qid, ['uid', 'hash', 'status', 'question_data', 'order_num']);

        if ($questionData['uid'] !== $this->user['id'] || $questionData['status'] > 1)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $recodes = [];
        if ($questionData['question_data']['recode1'])
        {
            $record1 = $questionData['question_data']['recode1'];
            $recodes[] = [
                'id' => $record1['id'],
                'avatar' => $record1['avatar'],
                'name' => $record1['name'] . ($record1['isself'] === 1 ? '（自己）' : ''),
                'brithday' => sprintf("%d-%02d-%02d %02d:%02d", $record1['year'], $record1['month'], $record1['day'], $record1['hour'], $record1['minute']),
                'address' => "{$record1['birth_country']} {$record1['birth_province']} {$record1['birth_city']}",
            ];
        }
        if ($questionData['question_data']['recode2'])
        {
            $record2 = $questionData['question_data']['recode2'];
            $recodes[] = [
                'id' => $record2['id'],
                'avatar' => $record2['avatar'],
                'name' => $record2['name'] . ($record2['isself'] === 1 ? '（自己）' : ''),
                'brithday' => sprintf("%d-%02d-%02d %02d:%02d", $record2['year'], $record2['month'], $record2['day'], $record2['hour'], $record2['minute']),
                'address' => "{$record2['birth_country']} {$record2['birth_province']} {$record2['birth_city']}",
            ];
        }

        $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionData['hash'], ['price', 'name', 'img']);

        $pay_mode_list = [
            [
                'trade_type' => 1,
                'name' => '支付宝支付',
                'icon' => '/mini/astrolabe/order/alipay.png',
                'is_selected' => 1,
            ],
            [
                'trade_type' => 2,
                'name' => '微信支付',
                'icon' => '/mini/astrolabe/order/wechat.png',
                'is_selected' => 0,
            ],
        ];

        if ($this->isWexinBrowser())
        {
            $pay_mode_list = [
                [
                    'trade_type' => 3,
                    'name' => '微信支付',
                    'icon' => '/mini/astrolabe/order/wechat.png',
                    'is_selected' => 1,
                ]
            ];
        }

        return show(config('code.success'), '请求成功', [
            'recode_list' => $recodes,
            'good_info' => [
                'img' => $goodInfo['img'],
                'name' => $goodInfo['name'],
                'price' => $goodInfo['price'],
            ],
            'pay_mode_list' => $pay_mode_list
        ]);
    }

    /**
     * 下单支付 与 继续支付
     * @return Json
     * @throws ApiException
     */
    public function orderPay()
    {
        $qid = input('qid/d', 0);
        $tradeType = input('trade_type/d', 0);  // 1=>支付宝支付,2=>微信网页支付,3=>微信js支付
        $callbackUrl = input('callback_url/s', '');
        $openid = input('openid/s', '');
        $code = input('code/s', '');
        if (!$tradeType)
        {
            return show(config('code.error'), '请选择支付方式！');
        }
        if (!$qid || !in_array($tradeType, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $questionInfoModel = new PrivateAreaQuestionInfo();
        $goodModel = new PrivateAreaGoods();

        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($qid, ['uid', 'hash', 'status', 'order_num']);
        if (!$questionInfo || $questionInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，咨询问题不存在～');
        }

        if ($questionInfo['status'] > 1)
        {
            return show(config('code.error'), '咨询订单状态异常～');
        }

        $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionInfo['hash'], ['lid', 'name', 'price', 'channel_id', 'type']);

        $orderId = $questionInfo['order_num'];
        $type = 50 + $goodInfo['type'];
        if ($questionInfo['status'] === 0)
        {  // 待下单
            try
            {
                Db::startTrans();
                $insert = [
                    'uid' => $this->user['id'],
                    'qid' => $qid,
                    'good_type' => $goodInfo['type'],
                    'order_id' => str_pad($type, 2, '0', STR_PAD_LEFT) . date('YmdHis') . str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT),
                    'trade_type' => $tradeType,
                    'total_amount' => $goodInfo['price'],
                    'create_time' => $this->request->time(),
                    'status' => 1,
                    'channel' => $goodInfo['channel_id'],
                ];
                $orderId = $insert['order_id'];

                $oid = (new PrivateAreaOrders())->insertDataGetId($insert);

                if (!$oid)
                {
                    return show(config('code.error'), '服务异常，下单失败～');
                }
                // 更新链接 信息
                $goodModel->updatePrivateAreaLinkData($questionInfo['hash'], $goodInfo['lid'], ['order_num' => $insert['order_id']]);
                // 更新咨询 信息
                $questionInfoModel->updateUserQuestionData($qid, [
                    'order_num' => $insert['order_id'],
                    'status' => 1
                ]);

                Db::commit();
            }
            catch (\Exception $e)
            {
                Db::rollback();
                Log::write('私域H5 订单 下单 失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            }
            // 添加 订单支付检测 队列
            PushQueue::CloseOrder($orderId, 7200);
        } elseif ($questionInfo['status'] === 1)
        {
            (new PrivateAreaOrders())->updateOrderInfo($orderId, ['trade_type' => $tradeType]);
        }

        if (3 === $tradeType)
        {//如果是微信支付，那么如果存在openid，那么为微信js支付
//            $tradeType = $openid ? 3 : 2;
            // 微信JSAPI支付
            if (empty($openid))
            {   // 如果openid没有，那么通过传过来的code获取access_token，然后再获取openid
                if (!empty($code))
                {   // 去换取用户openid
                    $wxConfig = config('wechat');
                    $wechatConfig = [
                        'appid' => $wxConfig['mp_appid'],
                        'secret' => $wxConfig['mp_secret']
                    ];

                    $wxInfo = $this->wechatGetAccessTokenAndOpenidByCode($wechatConfig, $code);
                    if (!$wxInfo || isset($wxInfo['errcode']))
                    {
                        Log::write("获取Access_token错误：" . json_encode($wxInfo), 'error');
                        return show(config('code.error'), $wxInfo['errmsg']);
                    }

                    $openid = $wxInfo['openid'] ?? '';
                } else
                { // 异常抛出
                    return show(config('code.error'), 'code不能为空！');
                }
            }
        }

        $tradeTypeConfig = [
            1 => 7,
            2 => 8,
            3 => 6
        ];

        //支付订单
        $arr = OrdersLib::unifyPayOrder([
            'oid' => $orderId,
            'trade_type' => $tradeTypeConfig[$tradeType],
            'total_amount' => $goodInfo['price'],
            'pay_des' => $goodInfo['name'],
            'order_id' => $orderId, // 订单编号
            'openid' => $openid,
            'callback_url' => $callbackUrl,
            'order_type' => $type,
            'uid' => (int)($this->user['id']),
        ], 1);

        if ($arr['status'])
        {
            $arr['data']['openid'] = $openid;
            return show(config('code.success'), '请求成功', $arr['data']);
        } else
        {
            Log::write('私域H5 订单 下单 调取支付数据失败【OrdersLib::unifyPayOrder】：' . json_encode($arr, JSON_UNESCAPED_UNICODE), 'error');
            return show(config('code.error'), '服务异常，下单失败～');
        }
    }

    /**
     * 订单支付状态查询
     */
    public function getOrderStatus()
    {
        $orderId = input('order_id/s', '');

        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId, ['uid', 'status']);

        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }

        return show(config('code.success'), '请求成功', ['status' => $orderInfo['status'] === 1 ? 0 : 1]);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $orderId = input('order_id/s', '');

        $questionInfoModel = new PrivateAreaQuestionInfo();
        $goodModel = new PrivateAreaGoods();
        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId, ['uid', 'status', 'qid', 'create_time', 'trade_type', 'pay_time', 'return_amount', 'return_time']);

        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }

        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($orderInfo['qid'], ['uid', 'hash', 'status', 'order_num']);
        $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionInfo['hash'], ['name', 'img', 'price', 'type']);


        if (in_array($orderInfo['status'], [1, 3, 5], true))
        {   // 待支付 || 未支付订单关闭
            $endTime = 0;
            if ($orderInfo['status'] === 1)
            {
                $endTime = $orderInfo['create_time'] + 7200 - $this->request->time();
            }
            $statusText = [
                1 => [
                    'status' => 1,
                    'des' => '等待支付'
                ],
                3 => [
                    'status' => 0,
                    'des' => '订单关闭'
                ],
                5 => [
                    'status' => 6,
                    'des' => '退款成功'
                ],
            ];
            $resData = [
                'status' => $statusText[$orderInfo['status']]['status'],
                'end_time' => $endTime > 0 ? $endTime : 0,
                'des' => $statusText[$orderInfo['status']]['des'],
                'price' => $goodInfo['price'],
                'qid' => $orderInfo['qid']
            ];
            $resData['info_list'] = [
                [
                    'type' => 1,
                    'value_data' => [
                        'img' => $goodInfo['img'],
                        'name' => $goodInfo['name'],
                        'price' => $goodInfo['price'],
                    ]
                ],
                // [
                //     'type' => 2,
                //     'value_data' => [
                //         [
                //             'title' => '商品类型',
                //             'des' => $goodModel->goodTypeName[$goodInfo['type']],
                //             'value_type' => 0,
                //             'value' => 0,
                //         ]
                //     ]
                // ],
                [
                    'type' => 2,
                    'value_data' => [
                        [
                            'title' => '购买信息',
                            'des' => '查看更多',
                            'value_type' => 2,
                            'value' => $orderInfo['qid'],
                        ]
                    ]
                ],
                [
                    'type' => 2,
                    'value_data' => [
                        [
                            'title' => '订单编号',
                            'des' => $orderId,
                            'value_type' => 3,
                            'value' => 0,
                        ]
                    ]
                ],
            ];

            if ($orderInfo['status'] === 1)
            {
                if ($this->isWexinBrowser())
                {
                    $resData['pay_mode_list'] = [
                        [
                            'trade_type' => 3,
                            'name' => '微信支付',
                            'icon' => '/mini/astrolabe/order/wechat.png',
                            'is_selected' => 1,
                        ]
                    ];
                } else
                {
                    // 待支付
                    $resData['pay_mode_list'] = [
                        [
                            'trade_type' => 1,
                            'name' => '支付宝支付',
                            'icon' => '/mini/astrolabe/order/alipay.png',
                            'is_selected' => 1,
                        ],
                        [
                            'trade_type' => 2,
                            'name' => '微信支付',
                            'icon' => '/mini/astrolabe/order/wechat.png',
                            'is_selected' => 0,
                        ],
                    ];
                }
            } else
            {
                // 订单关闭
                $resData['info_list'][1]['value_data'][] = [
                    'title' => '实付金额',
                    'des' => '¥' . $goodInfo['price'],
                    'value_type' => 0,
                    'value' => 0,
                ];

                if ($orderInfo['status'] === 5)
                {   // 退款
                    $resData['info_list'][2]['value_data'][] = [
                        'title' => '支付方式',
                        'des' => $orderInfo['trade_type'] === 1 ? '支付宝' : '微信',
                        'value_type' => 0,
                        'value' => 0,
                    ];
                    $resData['info_list'][2]['value_data'][] = [
                        'title' => '支付时间',
                        'des' => date('Y-m-d H:i', $orderInfo['pay_time']),
                        'value_type' => 0,
                        'value' => 0,
                    ];
                    $resData['info_list'][] = [
                        'type' => 2,
                        'value_data' => [
                            [
                                'title' => '退款时间',
                                'des' => date('Y-m-d H:i', $orderInfo['return_time']),
                                'value_type' => 0,
                                'value' => 0,
                            ], [
                                'title' => '退款金额',
                                'des' => '¥' . $orderInfo['return_amount'],
                                'value_type' => 0,
                                'value' => 0,
                            ],
                        ]

                    ];
                }
            }
        } else
        {
            $questionStatusText = [
                2 => [
                    'status' => 2,
                    'des' => '支付成功，请耐心等待占星师接单'
                ],
                4 => [
                    'status' => 3,
                    'des' => '占星师已接单，请耐心等待回复'
                ],
                5 => [
                    'status' => 3,
                    'des' => '占星师已接单，请耐心等待回复'
                ],
                6 => [
                    'status' => 3,
                    'des' => '占星师已接单，请耐心等待回复'
                ],
                7 => [
                    'status' => 4,
                    'des' => '占星师回复结果，点击查看结果'
                ],
                8 => [
                    'status' => 5,
                    'des' => '订单已完成'
                ],
            ];
            $resData = [
                'status' => $questionStatusText[$questionInfo['status']]['status'],
                'end_time' => 0,
                'des' => $questionStatusText[$questionInfo['status']]['des'],
                'info_list' => [
                    [
                        'type' => 2,
                        'value_data' => [
                            // [
                            //     'title' => '商品类型',
                            //     'des' => $goodModel->goodTypeName[$goodInfo['type']],
                            //     'value_type' => 0,
                            //     'value' => 0,
                            // ],
                            [
                                'title' => '商品名称',
                                'des' => $goodInfo['name'],
                                'value_type' => 1,
                                'value' => $questionInfo['hash'],
                            ],
                            [
                                'title' => '实付金额',
                                'des' => '¥' . $goodInfo['price'],
                                'value_type' => 0,
                                'value' => 0,
                            ],
                        ]
                    ],
                    [
                        'type' => 2,
                        'value_data' => [
                            [
                                'title' => '购买信息',
                                'des' => '查看更多',
                                'value_type' => 2,
                                'value' => $orderInfo['qid'],
                            ]
                        ]
                    ],
                    [
                        'type' => 2,
                        'value_data' => [
                            [
                                'title' => '订单编号',
                                'des' => $orderId,
                                'value_type' => 3,
                                'value' => 0,
                            ],
                            [
                                'title' => '支付方式',
                                'des' => $orderInfo['trade_type'] === 1 ? '支付宝' : '微信',
                                'value_type' => 0,
                                'value' => 0,
                            ],
                            [
                                'title' => '支付时间',
                                'des' => date('Y-m-d H:i', $orderInfo['pay_time']),
                                'value_type' => 0,
                                'value' => 0,
                            ]
                        ]
                    ]
                ]
            ];

        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $page = input('page/d', 1);

        $page = $page < 1 ? 1 : $page;

        $data = (new PrivateAreaOrders())->getOrderList($this->user['id'], $page);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 取消订单
     */
    public function closeOrder()
    {
        $orderId = input('order_id/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId, ['uid', 'status', 'qid', 'order_id']);

        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }

        if ($orderInfo['status'] !== 1)
        {
            return show(config('code.error'), '订单状态异常，订单取消失败～');
        }

        $OrdersLib = new OrdersLib();

        $OrdersLib::privateAreaCloseOrder($orderInfo);

        return show(config('code.success'), '订单取消成功');
    }
}
